package com.xypower.link;

//将单向链表按某值划分成左变小，中间相等，右边大的形式
public class SmallerEqualBigger {
    public static class Node{
        public int value;
        public Node next;
        public Node(int data){
            this.value = data;
        }
    }
    //解法1
    public static Node listPartition1(Node head,int pivot){
        if (head == null){
            return head;
        }
        Node cur = head;
        int i = 0;
        while (cur != null){
            i++;
            cur = cur.next;
        }
        Node[] nodeArr = new Node[i];
        i = 0;
        cur = head;
        for (i=0;i!=nodeArr.length;i++){
            nodeArr[i] = cur;
            cur =  cur.next;
        }
        arrPartition(nodeArr,pivot);
        for (i=1;i!=nodeArr.length;i++){
            nodeArr[i-1].next=nodeArr[i];
        }
        nodeArr[i-1].next=null;
        return nodeArr[0];
    }

    public static void arrPartition(Node[] nodeArr,int pivot){
        int small = -1;
        int big = nodeArr.length;
        int index = 0;
        while (index != big){
            if (nodeArr[index].value<pivot){
                swap(nodeArr,++small,index++);
            }else if (nodeArr[index].value== pivot){
                index++;
            }else {
                swap(nodeArr,--big,index);
            }
        }
    }

    public static void swap(Node[] nodeArr,int a,int b){
        Node tmp = nodeArr[a];
        nodeArr[a] = nodeArr[b];
        nodeArr[b] = tmp;
    }
    //最优解 解法2
    public static Node listPartition2(Node head,int pivot){
        Node sH = null;
        Node sT = null;
        Node eH = null;
        Node eT = null;
        Node mH = null;
        Node mT = null;
        Node next = null;

        while (head != null){
            next = head.next;
            head.next = null;
            if (head.value < pivot){
                if (sH==null){//如果是第一个节点
                    sH = head;
                    sT = head;
                }else {
                    sT.next = head;
                    sT = head;
                }
            }else if (head.value==pivot){
                if (eH==null){
                    eH=head;
                    eT=head;
                }else {
                    eT.next = head;
                    eT = head;
                }
            }else {
                if (mH==null){
                    mH = head;
                    mT = head;
                }else {
                    mT.next = head;
                    mT = head;
                }
            }
            head = next;
        }
        //连接
        if (sT!=null){//如果又小于区域
            sT.next = eH;
            eT = eT==null?sT:eT;
        }

        if (eT!=null){//如果小于区域和等于区域,不是都没有
            eT.next=mH;
        }
        return sH!=null ? sH:(eH!=null?eH:mH);
    }
}
